package com.muc.plugin.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.jivesoftware.openfire.IQRouter;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.event.SessionEventListener;
import org.jivesoftware.openfire.muc.spi.LocalMUCRoom;
import org.jivesoftware.openfire.muc.spi.MultiUserChatServiceImpl;
import org.jivesoftware.openfire.session.Session;
import org.jivesoftware.openfire.vcard.VCardManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.IQ.Type;
import org.xmpp.packet.JID;

import com.muc.plugin.dao.MUCDao;

/**
 * 客户端用户的 session监听
 * <p>
 * 用户登录的时候,从数据库查询用户加入的房间. 创建session,自动把用户加入房间
 */
public class SessionEventListenerImpl implements SessionEventListener {

    private static final Logger log = LoggerFactory.getLogger(SessionEventListenerImpl.class);

    private MultiUserChatServiceImpl mucService;

    private XMPPServer server = XMPPServer.getInstance();

    private IQRouter router = XMPPServer.getInstance().getIQRouter();

    /**
     * 用户登录时
     */
    @Override
    public void sessionCreated(Session session) {
        log.info("@@@@@@@@@@@@@" + session.getAddress().toBareJID() + "登录了!");
        JID userJid = session.getAddress();
        joinRooms(userJid, session);
    }

    /**
     * 用户登录时执行
     * @param userJid
     * @param session
     */
    public void joinRooms(final JID userJid, final Session session) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


                List<Map<String, String>> data = MUCDao.getMUCInfo(userJid.toBareJID());

                if (data == null || data.isEmpty()) {
                    data = new ArrayList<>();
                }
                Map<String, String> map;

                /**
                 * 构建iq的扩展包，用于发送用户所在房间的名称。
                 */
                IQ iq = new IQ(Type.result);
                iq.setID(UUID.randomUUID().toString());
                iq.setTo(userJid.toFullJID());
                iq.setChildElement("muc", "xls:muc-user-joined-rooms");
                for (int i = 0, len = data.size(); i < len; i++) {
                    map = data.get(i);

                    String serviceID = map.get("serviceID");
                    mucService = (MultiUserChatServiceImpl) server
                            .getMultiUserChatManager().getMultiUserChatService(
                                    Long.parseLong(serviceID));
                    String roomName = map.get("name");
                    LocalMUCRoom room = (LocalMUCRoom) mucService.getChatRoom(roomName);

                    //增加room和account信息
                    Element room1 = iq.getChildElement().addElement("room");
                    room1.setText(room.getJID().toBareJID());
                    room1.addAttribute("account", userJid.toFullJID())
                            .addAttribute("roomId", room.getID() + "").addAttribute("description", room.getDescription())
                            .addAttribute("naturalName", room.getNaturalLanguageName());

                }
                //最后发送出去！
                log.info("@@@@@@@@@@@ success result: " + iq.toXML());
                session.process(iq);
            }
        }).start();
    }

    @Override
    public void sessionDestroyed(Session session) {
        // TODO Auto-generated method stub
        JID userJid =session.getAddress();
        //下线改变坐标
        Element cardElem = VCardManager.getInstance().getVCard(userJid.getNode());
        if (cardElem!=null) {
            Element adrElem = cardElem.element("latAndlon");
            cardElem.remove(adrElem);
            adrElem.setText(4.9E-324+","+4.9E-324);
            cardElem.add(adrElem);
            try {
                VCardManager.getInstance().setVCard(userJid.getNode(), cardElem);
            } catch (Exception e) {
                log.info(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    @Override
    public void anonymousSessionCreated(Session session) {
        // TODO Auto-generated method stub

    }

    @Override
    public void anonymousSessionDestroyed(Session session) {
        // TODO Auto-generated method stub

    }

    @Override
    public void resourceBound(Session session) {
        // TODO Auto-generated method stub

    }


    /**
     * 备用
     * 用户登录的时候,从数据库查询用户加入的房间. 创建session,自动把用户加入房间
     * <iq type="result" to="ycl5@192.168.27.39/Spark 2.6.3" id="MZH">
     * <muc xmlns="MZH">
     * <room xmlns="" account="ycl5@192.168.27.39/Spark 2.6.3">222@conference.192.168.27.39</room>
     * </muc></iq>
     */
    public void joinRooms(JID userJid) {
        List<Map<String, String>> roomMap = MUCDao.getMUCInfo(userJid.toBareJID());

        if (roomMap == null || roomMap.isEmpty()) {
            return;
        }
        Map<String, String> mapOfRoom;

        /**
         * 构建iq的扩展包，用于发送用户所在房间的名称。
         */
        Document document = DocumentHelper.createDocument();
        Element iqe = document.addElement("iq");
        iqe.addAttribute("type", "result");
        iqe.addAttribute("to", userJid.toFullJID());
        iqe.addAttribute("id", "MZH");

        Namespace namespace = new Namespace("", "MZH");
        Element muc = iqe.addElement("muc");
        muc.add(namespace);

        for (int i = 0, len = roomMap.size(); i < len; i++) {
            mapOfRoom = roomMap.get(i);

            String serviceID = mapOfRoom.get("serviceID");
            mucService = (MultiUserChatServiceImpl) server
                    .getMultiUserChatManager().getMultiUserChatService(
                            Long.parseLong(serviceID));
            String roomName = mapOfRoom.get("name");
            LocalMUCRoom room = (LocalMUCRoom) mucService.getChatRoom(roomName);

            // 增加room和,roomName,account信息
            Element room1 = muc.addElement("room");
            // room1.setText(room.getJID().toBareJID());
            room1.addAttribute("roomJid", room.getID()+"");
            room1.addAttribute("roomName", room.getName());
            room1.addAttribute("account", userJid.toFullJID());

            List<Map<String, String>> listRoom = MUCDao.getRoomInfo(mapOfRoom.get("roomId"));

            if (listRoom == null || listRoom.isEmpty()) {
                return;
            }
            Map<String, String> mapOfRoom1;
            for (int j = 0; j < listRoom.size(); j++) {

                mapOfRoom1 = listRoom.get(j);
                String jid = mapOfRoom1.get("jid");
                String nickName = mapOfRoom1.get("nickName");

                //在room节点中增加room1信息
                Element room2 = room1.addElement("friend");
                room2.setText(jid);
                room2.setText(nickName);
            }
        }
        // 最后发送出去！
        IQ iq = new IQ(iqe);
        log.info("@@@@@@@@@@@@@@@@@@ room iq : " + iq.toXML());
        router.route(iq);
    }

}
